package dongfeng.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.monitor.cache.Util.MD5;

public class DFAddEnterprise {
	public static Log log = LogFactory.getLog(DFAddEnterprise.class);

	// 新增人员
	public static JSONObject addHrmresourceAndDept(String userid, String qymc, String qyjc, String qyfr, String yddh) {
		log.info("=======================Start.");
		log.info("userid:" + userid + "|qymc:" + qymc);
		JSONObject resultObj = new JSONObject();// 返回参数
		if (qymc == null || qyjc == null || qyfr == null || yddh == null) {
			// 全部正常
			resultObj.put("code", -1);
			resultObj.put("msg", "传输参数错误");
			return resultObj;
		}
		if ("".equals(qymc) || "".equals(qyjc) || "".equals(qyfr) || "".equals(yddh)) {
			// 全部正常
			resultObj.put("code", -1);
			resultObj.put("msg", "传输参数错误");
			return resultObj;
		}

		// 获取当前日期、时间
		String currTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
		String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		RecordSet recordSet = new RecordSet();
		// 新建部门、人员时部分默认信息
		String subId = recordSet.getPropValue("DFZQXT", "subid"); // 默认分部ID
		String jobtitleId = recordSet.getPropValue("DFZQXT", "jobtitleId"); // 默认岗位ID
		int EnterpriseModeId = 45; // 企业信息模块ID
		int EPContactsModeId = 46; // 企业联系人模块ID
		String locationId = recordSet.getPropValue("DFZQXT", "locationId"); // 办公地点ID

		int systemlanguage = 7; // 系统预言int
		String maritalstatus = "0"; // 婚姻状况char，默认0
		int joblevel = 0; // int 工作级别
		String jobactivitydesc = "";// 职责描述
		int seclevel = 10;// 安全级别
		String workcode = "";// 编号
		Double dsporder = 0.0; // 显示顺序
		int accounttype = 0; // 账号类型
		int belongto = -1; // 所属主账号

		if (DeptExists(qymc)) {
			resultObj.put("code", 1);
			resultObj.put("msg", qymc + "部门已存在");
			return resultObj;
		}

		String bmid = null;
		// 判断法人是否存在
		String id = qyfrExists(qyfr, yddh);
		if (id == null) {
			RecordSetTrans recordSetTrans2 = new RecordSetTrans();
			String qyfrLoginId = null; // 创建的法人的人员ID
			try {
				bmid = CreateDept(recordSetTrans2, qyjc, qymc, GetAllFirstLetter.getAllFirstLetter(qymc), subId);
				if (bmid == null) {
					resultObj.put("code", 2);
					resultObj.put("msg", "创建" + qymc + "部门失败");
					return resultObj;
				}
				// 在刚刚创建的部门下-创建人员信息（如创建失败，则删除人员以及刚刚创建的部门信息）
				qyfrLoginId = CreateEmpt(recordSetTrans2, qyfr, yddh, bmid, subId, userid, jobtitleId, locationId,
						currDate);
				// 部门、人员创建完成后，更新下一个人员的生成ID
				UpdateHrmresourceID(recordSetTrans2, Integer.parseInt(qyfrLoginId));
				insertContacter(recordSetTrans2, userid, EPContactsModeId, currDate, currTime, bmid, qyjc, qyfr, yddh,
						qyfrLoginId);
				recordSetTrans2.commit();
				id = qyfrLoginId;// 赋值id
			} catch (Exception e) {
				log.info("创建人员or更新下一个人员的ID失败or创建联系人失败or更新权限失败");
				recordSetTrans2.rollback();
				resultObj.put("code", 3);
				resultObj.put("msg", "创建人员or更新下一个人员的ID失败");
				return resultObj;
			}
		} else {
			RecordSetTrans recordSetTrans2 = new RecordSetTrans();
			try {
				bmid = CreateDept(recordSetTrans2, qyjc, qymc, GetAllFirstLetter.getAllFirstLetter(qymc), subId);
				if (bmid == null) {
					resultObj.put("code", 2);
					resultObj.put("msg", "创建" + qymc + "部门失败");
					return resultObj;
				}
				insertContacter(recordSetTrans2, userid, EPContactsModeId, currDate, currTime, bmid, qyjc, qyfr, yddh,
						id);
				recordSetTrans2.commit();
			} catch (Exception e) {
				e.printStackTrace();
				recordSetTrans2.rollback();
				resultObj.put("code", 4);
				resultObj.put("msg", "创建联系人失败or更新权限失败");
				return resultObj;
			}
		}
		// 全部正常
		resultObj.put("code", 0);
		resultObj.put("msg", "ok");
		resultObj.put("bmhx", bmid);
		resultObj.put("qyfrhx", id);

		return resultObj;
	}

	/**
	 * 创建（企业）部门
	 * 
	 * @param qyjc          （企业）部门简称
	 * @param qymc          （企业）部门名称
	 * @param pinyin_search 快速搜索代码
	 * @return 创建后的部门ID
	 */
	private static String CreateDept(RecordSetTrans rSetTrans, String qyjc, String qymc, String pinyin_search,
			String subId) {
		try {
			log.info("创建部门开始");
			DepartmentComInfo deComInfo = new DepartmentComInfo();
			String createDP = "insert into HrmDepartment("
					+ "departmentmark,departmentname,subcompanyid1,ecology_pinyin_search,"
					+ "tlevel,supdepid,allsupdepid,showorder) " + "values (" + "'" + qyjc + "','" + qymc + "'," + subId
					+ ",'" + pinyin_search + "'," + "" + 2 + "," + 0 + "," + 0 + "," + 0 + ")";
			rSetTrans.executeUpdate(createDP);
			// rSetTrans.commit();
			log.info(createDP);
			// 移除部门缓存
			deComInfo.removeCache();
			deComInfo.removeCompanyCache();
			log.info("创建部门结束");
		} catch (Exception e) {
			e.printStackTrace();
			// rSetTrans.rollback();
			log.info("创建部门失败");
		}
		// RecordSet rSet1 = new RecordSet();
		// 根据名称查询没有封存的部门id
		String getDpid = "select id from HrmDepartment where departmentname='" + qymc + "' and isnull(canceled,0)<>1";
		log.info(getDpid);
		String bmid = null;// 返回空代表创建部门失败
		try {
			rSetTrans.executeQuery(getDpid);
			if (rSetTrans.next()) {
				bmid = Util.null2String(rSetTrans.getString("id"));
				log.info("本次新建的部门ID是:" + bmid);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bmid;
	}

	/**
	 * 根据企业名称判断企业是否存在
	 * 
	 * @param qymc
	 * @return
	 */
	private static boolean DeptExists(String qymc) {
		boolean flag = false;
		RecordSet rSet1 = new RecordSet();
		// 根据名称查询没有封存的部门id
		String getDpid = "select * from HrmDepartment where departmentname='" + qymc + "' and isnull(canceled,0)<>1";
		log.info("查询所创建的部门是否存在:" + getDpid);
		rSet1.execute(getDpid);
		if (rSet1.next()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 判断法人是否已存在OA中
	 * 
	 * @param qyfr
	 * @param yddh
	 * @return
	 */
	private static String qyfrExists(String qyfr, String yddh) {
		String id = null;
		RecordSet rSet1 = new RecordSet();

		String getDpid = "select * from hrmresource where lastname='" + qyfr + "' and mobile='" + yddh + "'";
		log.info("查询所创建的人:" + getDpid);
		rSet1.execute(getDpid);
		if (rSet1.next()) {
			id = rSet1.getString("id");
		}
		return id;
	}

	/**
	 * 产生新的人员信息编号
	 * 
	 * @return result
	 */
	private static int getHrmresourceID() {
		int result = -1;
		try {
			String sql = "select currentid from sequenceindex where indexdesc='resourceid'";
			RecordSet rs = new RecordSet();
			rs.execute(sql);
			while (rs.next())
				result = Util.getIntValue(rs.getString("currentid"), 0);
		} catch (Exception e) {
			log.error("获取新的人员信息编号错误");
		}
		log.info("本次获取的sequenceindex-ID为：" + result);
		return result;
	}

	/**
	 * 更新下个人员ID
	 * 
	 * @param id
	 */
	private static void UpdateHrmresourceID(RecordSetTrans rs, int id) throws Exception {
		String sql = "update sequenceindex set currentid='" + (id + 1) + "' " + "where indexdesc='resourceid'";
		log.info("SQL-UpdateHrmresourceID:" + sql);
		try {
			rs.execute(sql);
			// rs.commit();
		} catch (Exception e) {
			// rs.rollback();
			log.error("更新人员编号失败");
			throw new Exception("更新人员编号失败");
		}
	}

	/**
	 * 创建企业法人信息
	 * 
	 * @param recordSetTrans
	 * @param qyfr           法人姓名 （与密码一致）
	 * @param bmid           所属部门ID
	 * @param userid
	 * @param currDate
	 */
	public static String CreateEmpt(RecordSetTrans recordSetTrans, String qyfr, String yddh, String bmid, String subId,
			String userid, String jobtitleId, String locationId, String currDate) throws Exception {
		ResourceComInfo resourceComInfo = new ResourceComInfo();
		int hrmId = getHrmresourceID();
		try {
			log.info("创建人员开始");
			// 人力资源缓存对象
			String createHRM = "insert into HrmResource(" + " id,lastname,loginid,mobile,"
					+ "password,departmentid,jobtitle," + "status,subcompanyid1,createrid,createdate,locationid,"
					+ "systemlanguage,maritalstatus,joblevel,jobactivitydesc,seclevel,workcode,"
					+ "dsporder,accounttype,belongto,mobileshowtype) " + " values(" + hrmId + " , '" + qyfr + "' , '"
					+ qyfr + "' , '" + yddh + "'," + "'" + MD5.MD5Encode("1").toUpperCase() + "' , " + bmid + " , "
					+ jobtitleId + " , " + 1 + " , " + subId + " , " + userid + " , '" + currDate + "' ," + locationId
					+ "," + "7,'0',0,' ',10,' '," + hrmId + ",0,-1,2)";
			recordSetTrans.execute(createHRM);
			// recordSetTrans.commit();
			log.info("createHRM:" + createHRM);
			// 移除人力资源缓存
			resourceComInfo.removeCache();
			resourceComInfo.removeResourceCache();
			String queryHRMSQL = "select id from hrmresource where loginid = '" + qyfr + "' and mobile='"+yddh+"' and departmentid="+bmid;
			recordSetTrans.executeQuery(queryHRMSQL);
			if (recordSetTrans.next()) {
				return recordSetTrans.getString("id");
			}else {
				log.info("获取所创建人员的ID失败");
				throw new Exception("获取所创建人员的ID失败");
			}
			
		} catch (Exception e) {
			log.info(e);
			throw new Exception("插入人员失败");
		}
	}

	public static void insertContacter(RecordSetTrans recordSetTrans, String userid, int EPContactsModeId,
			String currDate, String currTime, String bmid, String qyjc, String qyfr, String yddh, String qyfrid)
			throws Exception {
		log.info("===往企业联系人模块写入法人数据开始===");
		int MODEDATACREATER = Integer.parseInt(userid); // 创建人（可更改，此处作为常量）
		int MODEDATACREATERTYPE = 0; // 创建人类型
		String sql = "insert into uf_EPContacts"
				+ "(formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,qymc,qyjc,lxr,lxdh,qyfr,lxrhx)"
				+ "values(" + EPContactsModeId + "," + MODEDATACREATER + "," + MODEDATACREATERTYPE + ",'" + currDate
				+ "','" + currTime + "'" + "," + bmid + ",'" + qyjc + "','" + qyfr + "','" + yddh + "'," + qyfrid + ","
				+ qyfrid +")";
		log.info("insert into uf_EPContacts sql :" + sql);
		recordSetTrans.execute(sql);
		String sql2 = "select id from uf_EPContacts where formmodeid=" + EPContactsModeId + " and modedatacreater="
				+ MODEDATACREATER + " and " + " modedatacreatertype=" + MODEDATACREATERTYPE
				+ " and modedatacreatedate='" + currDate + "' and modedatacreatetime='" + currTime + "' and" + " qymc="
				+ bmid + " and qyjc='" + qyjc + "' and lxr='" + qyfr + "' and lxdh='" + yddh + "' and qyfr=" + qyfrid
				+ " and lxrhx=" + qyfrid;
		log.info("insert into uf_EPContacts sql :" + sql);
		recordSetTrans.executeQuery(sql2);
		if (recordSetTrans.next()) {
			log.info("更新模块权限：" + sql);
			ModeRightInfo mri2 = new ModeRightInfo();
			mri2.rebuildModeDataShareByEdit(MODEDATACREATER, EPContactsModeId, recordSetTrans.getInt("id"));
		}
	}
}
